package edu.dlust.trading_platform;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.yalantis.ucrop.UCrop;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Date;

import edu.dlust.trading_platform.DataBase.MySQL;
import edu.dlust.trading_platform.DataBean.userdata;

public class MySpaceActivity extends AppCompatActivity {
    private ImageView back,my_img;
    private Button up,change;
    private EditText name,phone;
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected static Uri tempUri;
    private Bitmap mBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_space);


        back = findViewById(R.id.my_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MySpaceActivity.this.finish();
            }
        });

        initUI();
        get();
        update();

        if (userdata.getImg() != null){
            try {
                my_img.setImageBitmap(userdata.getImg());
            } catch (Exception e) {
            }
        }
    }


    private void initUI() {
        my_img = findViewById(R.id.my_img);
        up = findViewById(R.id.my_up);
        AddImg();
    }

    private void AddImg() {
        up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 检查并请求权限
                if (ContextCompat.checkSelfPermission(MySpaceActivity.this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(MySpaceActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(MySpaceActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MySpaceActivity.this,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                            100); // 请求码
                } else {
                    showChoosePicDialog();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showChoosePicDialog();
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MySpaceActivity.this);
        builder.setTitle("添加图片");
        String[] items = {"选择本地照片", "拍照"};
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case CHOOSE_PICTURE: // 选择本地照片
                        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        openAlbumIntent.setType("image/*");
                        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                        break;
                    case TAKE_PICTURE: // 拍照
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                        } catch (IOException ex) {
                            Log.e("PublishActivity", "Error creating image file: " + ex.getMessage());
                        }
                        if (photoFile != null) {
                            tempUri = FileProvider.getUriForFile(MySpaceActivity.this,
                                    BuildConfig.APPLICATION_ID + ".provider",
                                    photoFile);
                            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                            startActivityForResult(openCameraIntent, TAKE_PICTURE);
                        }
                        break;
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CHOOSE_PICTURE:
                    cutImage(data.getData()); // 对图片进行裁剪处理
                    break;
                case TAKE_PICTURE:
                    // 授予临时权限
                    if (tempUri != null) {
                        grantUriPermission(getPackageName(), tempUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    }
                    cutImage(tempUri); // 对图片进行裁剪处理
                    break;
                case UCrop.REQUEST_CROP:
                    final Uri resultUri = UCrop.getOutput(data);
                    setImageToView(resultUri);
                    break;
                case UCrop.RESULT_ERROR:
                    final Throwable cropError = UCrop.getError(data);
                    Log.e("UCrop", "Crop error: " + cropError);
                    break;
            }
        }
    }

    protected void cutImage(Uri uri) {
        if (uri == null) {
            Log.i("alanjet", "The uri is not exist.");
            return;
        }
        tempUri = uri;
        UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), "cropped_image.jpg")))
                .withAspectRatio(1, 1)
                .withMaxResultSize(150, 150)
                .start(MySpaceActivity.this);
    }

    protected void setImageToView(Uri uri) {
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            my_img.setImageBitmap(bitmap);
            mBitmap = bitmap;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        return image;
    }

    public byte[] HandleImg(Bitmap bitmap){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); // 也可以使用JPEG等其他格式
        return stream.toByteArray();
    }

    private void get(){
        name = findViewById(R.id.my_name);
        phone = findViewById(R.id.my_phone);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String str = "SELECT UName, Phone FROM LOGINID WHERE Uid = ?;";
                    Connection con = MySQL.getConnection();
                    PreparedStatement ps = con.prepareStatement(str);
                    ps.setString(1, userdata.getUid());
                    ResultSet rs = ps.executeQuery();
                    if(rs.next()){
                        String uname = rs.getString("UName");
                        String uphone = rs.getString("Phone");

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                name.setText(uname);
                                phone.setText(uphone);
                            }
                        });
                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MySpaceActivity.this, "出错啦！", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    con.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void update(){
        change = findViewById(R.id.my_change);
        change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String names = name.getText().toString();
                String phones = phone.getText().toString();

                if (mBitmap == null) {
                    try {
                        Drawable drawable = my_img.getDrawable();
                        mBitmap = ((BitmapDrawable) drawable).getBitmap();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (names.equals("") || phones.equals("")){
                    Toast.makeText(MySpaceActivity.this, "内容不能为空！", Toast.LENGTH_SHORT).show();
                }else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String sql = "UPDATE LOGINID SET UName = ?, Phone = ?, Image = ? WHERE Uid = ?;";
                            try{
                                Connection con = MySQL.getConnection();
                                PreparedStatement ps = con.prepareStatement(sql);
                                ps.setString(1,names);
                                ps.setString(2,phones);
                                byte[] image = HandleImg(mBitmap);
                                if (image != null){
                                    ps.setBytes(3,image);
                                }else {
                                    ps.setNull(3, Types.BLOB);
                                }
                                ps.setString(4,userdata.getUid());

                                int row = ps.executeUpdate();

                                if (row >= 1){
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(MySpaceActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                                            userdata.setName(names);
                                            userdata.setImg(mBitmap);
                                            MySpaceActivity.this.finish();
                                        }
                                    });
                                }else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(MySpaceActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }
        });
    }


}